/// @tags: Math
#include <cstdio>
#include <cstring>
#include <iostream>

using std::cin;
using std::cout;

namespace BlueQuantum {

typedef long long LL;

constexpr int N = 1e5 + 3;

template <uint P, typename baseType>
inline baseType qpow(baseType base, LL exp) {
  baseType ans(1);
  for (; exp; exp >>= 1, base = base * base % P)
    if (exp & 1) ans = base * ans % P;
  return ans;
}

template <uint P>
struct Complex {
  LL real, imag;

  inline Complex(LL real = 0, LL imag = 0) : real(real), imag(imag) {}

  inline Complex operator+(const Complex &rhs) const {
    return Complex((real + rhs.real) % P, (imag + rhs.imag) % P);
  }

  inline Complex operator-(const Complex &rhs) const {
    return Complex((real - rhs.real) % P, (imag - rhs.imag) % P);
  }

  inline Complex operator*(const Complex &rhs) const {
    return Complex((real * rhs.real - imag * rhs.imag) % P,
                   (real * rhs.imag + imag * rhs.real) % P);
  }

  inline Complex operator%(uint garbage) { return *this; }

  inline Complex inv() {
    LL s = qpow<P>((real * real + imag * imag) % P, P - 2);
    return Complex(real * s % P, -imag * s % P);
  }
};

template <uint P>
inline void solve(uint T) {
  const LL inv2 = (P + 1) >> 1;
  while (T--) {
    LL x, y, C;
    char m[11];
    cin >> x >> y >> m >> C;
    if ((LL)x * y == 0) {
      cout << "0\n";
      continue;
    }
    if ((LL)x * x + (LL)y * y >= C && strcmp(m, "+oo") == 0) {
      cout << "error\n";
      continue;
    }
    C %= P;
    if (C == 0) {
      (strcmp(m, "+oo") != 0) ? cout << "error\n" : cout << "0\n";
      continue;
    }
    Complex<P> p(x, y), w(1, 0);
    p = p * p * (Complex<P>(C, 0).inv());
    int ans;
    if (strcmp(m, "+oo"))
      ans = (LL)((w - qpow<P>(p, atoi(m) + 1)) * ((w - p).inv())).imag * inv2 % P;
    else {
      ans = (LL)((w) * (w - p).inv()).imag * inv2 % P;
    }
    cout << (ans + P) % P << '\n';
  }
}

inline int main() {
  uint T, P;
  cin >> T >> P;
  switch (P) {
    case 998244353:
      solve<998244353>(T);
      break;
    case 51745123:
      solve<51745123>(T);
      break;
    case 1000000007:
      solve<1000000007>(T);
      break;
  }
  return 0;
}

}  // namespace BlueQuantum

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("/tmp/CodeTmp/testdata.in", "r", stdin);
  freopen("/tmp/CodeTmp/testdata.out", "w", stdout);
#else
  freopen("recurrence.in", "r", stdin);
  freopen("recurrence.out", "w", stdout);
#endif
#endif

  std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  return BlueQuantum::main();
}
